<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="关联用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入关联用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="转账时的手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入转账时的手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待处理" value="待处理"></el-option>
          <el-option label="处理中" value="处理中"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
          <el-option label="格式错误" value="格式错误"></el-option>
          <el-option label="失败" value="失败"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:upload:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:upload:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:upload:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:upload:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="el-table-wrapper">
      <el-table v-loading="loading" :data="uploadList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" />
        <el-table-column label="关联用户ID" align="center" prop="userId" />
        <el-table-column label="用户手机号" align="center" prop="phone" />
        <el-table-column label="文件名" align="center" prop="fileName" />
        <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
            <el-tooltip v-if="scope.row.errorMessage" :content="scope.row.errorMessage" placement="top">
              <el-icon class="error-info-icon"><Warning /></el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="总数" align="center" prop="totalCount" />
        <el-table-column label="错误信息" align="center" prop="errorMessage">
          <template #default="scope">
            <el-popover
              v-if="scope.row.errorMessage"
              placement="top"
              trigger="hover"
              :width="300"
              popper-class="error-message-popover"
            >
              <template #default>
                <div class="error-message-content">{{ scope.row.errorMessage }}</div>
              </template>
              <template #reference>
                <div class="error-msg-truncate">
                  {{ scope.row.errorMessage.length > 15 ? scope.row.errorMessage.substring(0, 15) + '...' : scope.row.errorMessage }}
                </div>
              </template>
            </el-popover>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="原始文件路径" align="center" prop="originalFilePath">
          <template #default="scope">
            <el-link v-if="scope.row.originalFilePath" type="primary" @click="previewFileContent(scope.row.originalFilePath, '原始文件路径')">查看内容</el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="结果文件路径" align="center" prop="resultFilePath">
          <template #default="scope">
            <el-link v-if="scope.row.resultFilePath" type="primary" @click="previewFileContent(scope.row.resultFilePath, '结果文件路径')">查看内容</el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="删除标记" align="center" prop="isDeleted">
          <template #default="scope">
            <el-tag :type="scope.row.isDeleted === 1 || scope.row.isDeleted === '1' ? 'danger' : 'success'">
              {{ scope.row.isDeleted === 1 || scope.row.isDeleted === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:upload:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:upload:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />

    <!-- 添加或修改文件上传对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="uploadRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入关联用户ID" />
        </el-form-item>
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名" />
        </el-form-item>
        <el-form-item label="错误信息" prop="errorMessage">
          <el-input v-model="form.errorMessage" placeholder="请输入错误信息" />
        </el-form-item>
        <el-form-item label="上传时间" prop="uploadTime">
          <el-date-picker clearable
            v-model="form.uploadTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择上传时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总数" prop="totalCount">
          <el-input-number v-model="form.totalCount" :min="0" placeholder="请输入总数" />
        </el-form-item>
        <el-form-item label="原始文件上传" prop="uploadFile">
          <AnyFileUpload
            :drag="true"
            :file-size="100"
            :limit="10"
            :accept-all="true"
            @upload-success="handleFileUploadSuccess"
            @upload-error="handleFileUploadError"
            @upload-progress="handleUploadProgress"
          />
        </el-form-item>
        <el-form-item label="结果文件上传" prop="resultFile">
          <AnyFileUpload
            :drag="true"
            :file-size="100"
            :limit="10"
            :accept-all="true"
            @upload-success="handleResultFileUploadSuccess"
            @upload-error="handleFileUploadError"
            @upload-progress="handleUploadProgress"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="格式错误" value="格式错误"></el-option>
            <el-option label="失败" value="失败"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="删除标记" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择">
            <el-option :label="'否'" :value="0"></el-option>
            <el-option :label="'是'" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传进度" v-if="data.uploadProgress > 0">
          <el-progress 
            :percentage="data.uploadProgress"
            :status="data.uploadStatus === '上传成功' ? 'success' : ''"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览文件内容对话框 -->
    <el-dialog :title="previewTitle" v-model="previewOpen" width="700px" append-to-body>
      <div v-html="previewContent"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="copyToClipboard(previewContent)">
            <el-icon><CopyDocument /></el-icon> 复制内容
          </el-button>
          <el-button @click="previewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Upload">
import { listUpload, getUpload, delUpload, addUpload, updateUpload } from "@/api/checksystem/upload";
import { ElMessage } from 'element-plus'
import { formatDate } from '@/utils/format'
import Editor from '@/components/Editor'
import AnyFileUpload from '@/components/AnyFileUpload'
import { getToken } from "@/utils/auth"
import { UploadFilled, CopyDocument, Warning } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance();

const uploadList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const previewOpen = ref(false);
const previewContent = ref("");
const previewTitle = ref("文件内容预览");
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/service/upload "); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);

// 状态标签映射
const statusMap = {
  'pending': { type: 'info', text: '待处理' },
  'processing': { type: 'warning', text: '处理中' },
  'completed': { type: 'success', text: '已完成' },
  'failed': { type: 'danger', text: '失败' },
  '已完成': { type: 'success', text: '已完成' },
  '格式错误': { type: 'danger', text: '格式错误' },
  '处理中': { type: 'warning', text: '处理中' },
  '待处理': { type: 'info', text: '待处理' }
};

// 获取状态标签类型
const getStatusType = (status) => {
  if (!status) return 'info'; // 处理null或空字符串
  return statusMap[status]?.type || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  if (!status) return '未知'; // 处理null或空字符串
  return statusMap[status]?.text || status;
};

// 添加选项数据
const statusOptions = [
  { label: '上传中', value: 0 },
  { label: '上传成功', value: 1 },
  { label: '上传失败', value: 2 }
]

const isDeletedOptions = [
  { label: '未删除', value: 0 },
  { label: '已删除', value: 1 }
]

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    fileName: null,
    uploadTime: null,
    status: null,
    totalCount: null,
    errorMessage: null,
    originalFilePath: null,
    resultFilePath: null,
    isDeleted: null,
    orderByColumn: "uploadTime",  // 按上传时间排序
    isAsc: "desc"  // 倒序排列，最新的在前面
  },
  rules: {
    userId: [
      { required: true, message: "关联用户ID不能为空", trigger: "blur" }
    ],
    fileName: [
      { required: true, message: "文件名不能为空", trigger: "blur" },
      { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    uploadTime: [
      { required: true, message: "上传时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    isDeleted: [
      { required: true, message: "删除标记不能为空", trigger: "blur" }
    ]
  },
  uploadProgress: 0,
  uploadStatus: ''
});

const { queryParams, form, rules } = toRefs(data);

/** 查询文件上传列表 */
function getList() {
  loading.value = true;
  listUpload(queryParams.value).then(response => {
    uploadList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    loading.value = false;
    proxy.$message.error(`加载数据失败: ${error.message || '未知错误'}`);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    phone: null, // 用户手机号
    fileName: null,
    uploadTime: formatDate(new Date()), // 默认为当前日期
    status: '待处理', // 默认待处理
    totalCount: 0,
    errorMessage: null,
    originalFilePath: null, // 原始文件路径
    resultFilePath: null, // 结果文件路径
    createTime: null,
    updateTime: null,
    isDeleted: 0 // 默认为未删除
  };
  // 重置上传状态
  data.uploadProgress = 0;
  data.uploadStatus = '';
  
  proxy.resetForm("uploadRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文件上传";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUpload(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文件上传";
  });
}

/** 表单提交 */
function submitForm() {
  proxy.$refs["uploadRef"].validate(valid => {
    if (valid) {
      // 确保富文本内容正确提交
      if (form.value.id != null) {
        updateUpload(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUpload(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除文件上传编号为"' + _ids + '"的数据项？').then(function() {
    return delUpload(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('checksystem/upload/export', {
    ...queryParams.value
  }, `upload_${new Date().getTime()}.xlsx`)
}

// 添加文件上传进度监控
const handleUploadProgress = (event) => {
  data.uploadProgress = Math.round(event.percent)
  data.uploadStatus = event.percent === 100 ? '上传成功' : '上传中'
}

// 获取文件URL
function getFileUrl(path) {
  if (!path) return '';
  if (path.startsWith('http')) return path;
  return import.meta.env.VITE_APP_BASE_API + path;
}

// 预览文件内容
function previewFileContent(content, titlePrefix = "") {
  previewContent.value = content;
  previewTitle.value = titlePrefix ? `${titlePrefix} - 内容预览` : "文件内容预览";
  previewOpen.value = true;
}

// 文件上传成功处理
function handleFileUploadSuccess(result) {
  const { res, file } = result;
  if (res.code === 200) {
    proxy.$modal.msgSuccess("上传成功");
    // 获取文件路径
    const filePath = res.fileName || res.url || res.data;
    // 保存到表单中
    form.value.originalFilePath = filePath;
    form.value.fileName = file.name;
    // 显示路径信息
    showPathDialog(filePath, "原始文件路径");
    data.uploadStatus = '上传成功';
  } else {
    data.uploadStatus = '上传失败';
    proxy.$modal.msgError(res.msg || "上传失败");
  }
}

// 结果文件上传成功处理
function handleResultFileUploadSuccess(result) {
  const { res, file } = result;
  if (res.code === 200) {
    proxy.$modal.msgSuccess("结果文件上传成功");
    // 获取文件路径
    const filePath = res.fileName || res.url || res.data;
    // 保存到表单中
    form.value.resultFilePath = filePath;
    // 显示路径信息
    showPathDialog(filePath, "结果文件路径");
    data.uploadStatus = '上传成功';
  } else {
    data.uploadStatus = '上传失败';
    proxy.$modal.msgError(res.msg || "上传失败");
  }
}

// 文件上传失败处理
function handleFileUploadError(err) {
  data.uploadStatus = '上传失败';
  proxy.$modal.msgError("文件上传失败");
}

// 显示文件路径对话框
function showPathDialog(path, title) {
  proxy.$confirm(
    `<div style="word-break: break-all;">${path}</div>`,
    title,
    {
      confirmButtonText: '复制路径',
      cancelButtonText: '关闭',
      dangerouslyUseHTMLString: true,
      center: true,
      callback: (action) => {
        if (action === 'confirm') {
          // 复制路径到剪贴板
          navigator.clipboard.writeText(path).then(() => {
            proxy.$message.success('路径已复制到剪贴板');
          }).catch(err => {
            console.error('复制失败: ', err);
            proxy.$message.error('复制失败，请手动复制');
          });
        }
      }
    }
  );
}

// 复制文本到剪贴板
function copyToClipboard(text) {
  navigator.clipboard.writeText(text).then(() => {
    proxy.$message.success('已复制到剪贴板');
  }).catch(() => {
    proxy.$message.error('复制失败，请手动复制');
  });
}

getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-form--inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

.el-form--inline .el-form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.el-form-item__label {
  white-space: nowrap;
  min-width: 120px;
  line-height: 32px;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
}

.error-info-icon {
  margin-left: 5px;
  color: #E6A23C;
  cursor: pointer;
}

.el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-message-content {
  padding: 8px;
  font-size: 14px;
  color: #f56c6c;
}

.error-msg-truncate {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  color: #f56c6c;
  text-decoration: underline;
}

.error-message-popover {
  max-width: 300px;
  word-break: break-all;
}

/* 改进状态标签的样式 */
.el-tag.el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
  font-weight: bold;
}

.el-tag.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
  font-weight: bold;
}

.el-tag.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
  font-weight: bold;
}

.el-tag.el-tag--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
  font-weight: bold;
}

/* 分页样式 */
.pagination-container {
  position: fixed;
  bottom: 0;
  left: 200px;
  right: 0;
  background-color: #fff;
  padding: 15px 20px;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #dcdfe6;
}

/* 表格容器样式 */
.el-table-wrapper {
  margin-bottom: 80px;
}
</style>
